package com.fjsh.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.fjsh.base.handler.RouteHandler;
import com.fjsh.entity.AppRoute;
import com.fjsh.mapper.AppRouteMapper;
import com.fjsh.service.AppRouteService;
import com.fjsh.service.RouteDefinitionCacheService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class AppRouteServiceImpl implements AppRouteService {

    private static final Logger logger = LoggerFactory.getLogger(AppRouteService.class);

    @Resource
    private AppRouteMapper appRouteMapper;

    @Autowired
    private RouteDefinitionCacheService cacheService;

    @Autowired
    private RouteHandler routeHandler;

    @Override
    public List<AppRoute> findAll() {
        return appRouteMapper.findAll();
    }

    @Override
    public boolean saveOrUpdate(AppRoute route) {
        route.setUpdateTime(new Date());
        AppRoute oldRoute = appRouteMapper.findByRouteId(route.getRouteId());
        boolean res;
        if (oldRoute != null && ObjectUtil.equal(oldRoute.getRouteId(),route.getRouteId())) {
            res = appRouteMapper.update(route);
        } else {
            res = appRouteMapper.insertAppRoute(route);
        }

        if (res) {
            logger.info("更新缓存，通知网关重新加载路由信息...");
            cacheService.save(route.parseToRoute());
            routeHandler.loadRouteConfig();
        }

        return res;
    }

    @Override
    public boolean delete(AppRoute route) {
        route.setUpdateTime(new Date());
        boolean res = appRouteMapper.delete(route);
        if (res) {
            logger.info("更新缓存，通知网关重新加载路由信息...");
            cacheService.save(route.parseToRoute());
            routeHandler.loadRouteConfig();
        }
        return res;
    }

    @Override
    public AppRoute findByRouteId(String routeId) {
        return appRouteMapper.findByRouteId(routeId);
    }

}